package cn.kgc.day04.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author 课工场
 * @date 2024/10/11
 * @description  jdbc操作工具类   获取连接  释放资源
 */
public class JDBCUtil {

    private static DataSource dataSource;

    // 构造方法私有化   new JDBCUtil()
    private JDBCUtil(){ }

    static {
        InputStream resourceAsStream = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    // 获取连接池
    public static DataSource getDataSource(){
        return dataSource;
    }

    // 获取连接
    public static Connection createConnection(){

        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    // 释放资源
    public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {

        try {
            if (connection!=null){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if (statement!=null){
                statement.close();
            }
        } catch (SQLException e) {
           e.printStackTrace();
        }

        try {
            if (statement!=null){
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
